//
//  YSRequestConfig.m
//  p4
//
//  Created by Yuxin on 14/11/4.
//  Copyright (c) 2014年 me.yang-yuxin. All rights reserved.
//

#import "YSRequestConfig.h"

#define SERVICEKEY @"servicekey"

@interface YSRequestConfig() {
    NSDictionary * _Nonnull _config;
}

@end

CGFloat const kYSDefaultUploadImageCompressionQuality = 1;
NSString const * kYSDefaultUploadImageName = @"attachment";
NSString const * kYSDefaultUploadImageType = @"image/jpeg";

@implementation YSRequestConfig

+ (nonnull instancetype)shared
{
    static YSRequestConfig *config = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        config = [[self alloc] init];
    });
    return config;
}

- (nonnull NSString *)configName
{
    NSString *defaultName = @"service";
    if (_configName == nil) {
        _configName = defaultName;
    }
    return _configName;
}

- (nonnull NSDictionary *)config
{
    if (_config == nil) {
        NSString *serviceConfigJsonFile = [[NSBundle mainBundle] pathForResource:self.configName ofType:@"json"];
        if (serviceConfigJsonFile == nil) {
            serviceConfigJsonFile = [[NSBundle bundleForClass:[self class]] pathForResource:self.configName ofType:@"json"];
        }
        NSError *error = nil;
        NSDictionary *serviceConfig = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:serviceConfigJsonFile] options:NSJSONReadingAllowFragments error:&error];
        if (error != nil) {
            abort();
        }
        _config = serviceConfig;
    }
    return _config;
}

- (nonnull NSString *)urlStringFromName: (nonnull NSString *)pathName
{
    NSArray *nameArray = [pathName componentsSeparatedByString:@"."];
    NSString *category = nameArray[0];
    NSString *name = nameArray[1];
    NSString *serviceKey = self.serviceKey;
    NSDictionary *urlItem = (NSDictionary *)self.config[@"service"][category][name];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", self.config[@"domains"][serviceKey][urlItem[@"domain"]], urlItem[@"path"]];
    
    return url;
}

- (CGFloat)defaultUploadImageCompressionQuality
{
    return _defaultUploadImageCompressionQuality > 0 && _defaultUploadImageCompressionQuality <= 1? _defaultUploadImageCompressionQuality : kYSDefaultUploadImageCompressionQuality;
}

- (NSString *)defaultUploadImageName
{
    return _defaultUploadImageName ? : kYSDefaultUploadImageName;
}

- (NSString *)defaultUploadImageType
{
    return _defaultUploadImageType ? : kYSDefaultUploadImageType;
}

- (YSRequestHookExtraParamBlock)hookExtraParamBlock
{
    if (_hookExtraParamBlock) {
        return _hookExtraParamBlock;
    }
    return ^(){
        return @{};
    };
}

@end
